package com.tanhua.sso.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/7/11 22:24
 */

@Service
public class MyCenterService {

    @Autowired
    private UserService userService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 发送短信验证码：
     *
     * @param token
     * @return
     */
    public Boolean sendVerificationCode(String token) {

        User user = userService.queryUserByToken(token);
        if (ObjectUtil.isEmpty(user)) {
            return false;
        }

        //token有效：调用发短信的服务：

        String mobile = user.getMobile();
        ErrorResult errorResult = smsService.sendCheckMsg(mobile);
        if (errorResult == null) {
            //没有error对象返回，代表发送成功。
            return true;
        }

        return false;
    }


    /**
     * 校验短信验证码：
     *
     * @param code
     * @return
     */
    public Boolean checkVerificationCode(String code, String token) {

        //校验token：
        User user = userService.queryUserByToken(token);
        if (!ObjectUtil.isNotEmpty(user)) {
            return false;
        }

        //从redis获取value:
        String redisKey = "CHECK_CODE" + user.getMobile();

        String value = redisTemplate.opsForValue().get(redisKey);
        if (StrUtil.equals(code, value)) {
            //验证码校验通过：删除redisKey:
            redisTemplate.delete(redisKey);
            return true;
        }

        return false;
    }


    /**
     * 保存新手机：
     *
     * @return
     */
    public Boolean saveNewPhone(String newPhone, String token) {

        //校验token
        User user = userService.queryUserByToken(token);
        if (ObjectUtil.isEmpty(user)) {
            return false;
        }

        Boolean b = userService.updatePhone(user.getId(), newPhone);

        if (b) {
            //更新手机号成功：将之前的redisKey 删除：
            String redisKey = "TANHUA_USER_PHONE" + user.getId();
            redisTemplate.delete(redisKey);
        }
        return b;
    }
}
